# $Id: protocol.tcl 19 2012-01-18 16:11:20Z nickoos85@gmail.com $

set ::altera(debug) 1
proc openSocket {ip port} {
        if { [catch {socket $ip $port} ::altera(idx)] } {
                puts "erreur : $::altera(idx)"
                exit
        } else {
		puts "Info : Connected at $::altera(ip):$::altera(port)"
        }

        fconfigure $::altera(idx) -buffering line
        fileevent $::altera(idx) readable [list event $::altera(idx)]

        altera:lancement
}

proc altera:autoconnect { } {
    if {[info exists ::altera(idx)]} { puts "Bot already connected"; after 15000 altera:autoconnect } else { puts "Trying connection ..."; openSocket $::altera(ip) $::altera(port) }
}

proc altera:sendRaw {raw} {
	if {[info exists ::altera(msgsend:count)]} { incr ::altera(msgsend:count) 1 } else { set ::altera(msgsend:count) 1 }
	if {[info exists ::altera(msgsend:byte)]} { incr ::altera(msgsend:byte) [string bytelength $raw] } else { set ::altera(msgsend:byte) [string bytelength $raw] }
	if {$::altera(debug) == 1} { puts "==> $raw" }
	puts $::altera(idx) "$raw"
}

proc altera:traiteRaw {raw} {
	if {[info exists ::altera(msgrcv:count)]} { incr ::altera(msgrcv:count) 1 } else { set ::altera(msgrcv:count) 1 }
	if {[info exists ::altera(msgrcv:byte)]} { incr ::altera(msgrcv:byte) [string bytelength $arg] } else { set ::altera(msgrcv:byte) [string bytelength $arg] }
	puts $::altera(idx) "$raw"
}

if {![info exists ::altera(idx)]} { altera:autoconnect }
